<template>
  <div class="inline-flex flex-wrap">
    <button
      v-for="color in localSwatches"
      :key="color"
      type="button"
      :style="{
        '--tw-ring-opacity': 1,
        '--tw-ring-color': color,
        backgroundColor: color,
      }"
      :class="{ 'ring ring-offset-1': color === modelValueLowerCase }"
      class="mb-2 mr-1.5 flex h-8 w-8 items-center justify-center rounded p-0.5"
      @click="selectColor(color)"
    >
      <Icon
        v-if="color === modelValueLowerCase"
        icon="Check"
        class="h-5 w-5"
        :style="{ color: getContrast(color) }"
      />
    </button>

    <IFormInput
      class="h-8 w-8 rounded p-0"
      :class="{ 'border-primary-500 ring-primary-500': isCustomColorSelected }"
      type="color"
      :rounded="false"
      :name="name"
      :model-value="isCustomColorSelected ? modelValueLowerCase : '#ffffff'"
      @input="customColorInputEventHandler"
    />

    <button
      v-show="allowRemove && modelValue"
      type="button"
      class="mb-2 ml-1.5 flex h-8 w-8 items-center justify-center rounded border border-neutral-300 bg-neutral-100 hover:bg-neutral-300"
      @click="removeRequested"
    >
      <Icon icon="X" class="h-5 w-5" />
    </button>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import debounce from 'lodash/debounce'

import { getContrast } from '@/Core/utils'

const props = defineProps({
  modelValue: String,
  name: String,
  allowRemove: { default: true, type: Boolean },
  allowCustom: { default: true, type: Boolean },
  swatches: Array,
})

const emit = defineEmits(['update:modelValue', 'input', 'remove-requested'])

const localSwatches = computed(() =>
  (props.swatches || []).map(color => color.toLowerCase())
)

const modelValueLowerCase = computed(() =>
  !props.modelValue ? null : props.modelValue.toLowerCase()
)

const isCustomColorSelected = computed(() => {
  if (!props.modelValue || !props.allowCustom) {
    return false
  }

  return (
    localSwatches.value.filter(color => color === modelValueLowerCase.value)
      .length === 0
  )
})

function selectColor(value) {
  emit('update:modelValue', value)
  emit('input', value)
}

function removeRequested() {
  selectColor(null)
  emit('remove-requested')
}

const customColorInputEventHandler = debounce(function (value) {
  selectColor(value)
}, 500)
</script>
